package com.oriole.common.controller;

import com.oriole.common.constant.ResultModel;
import com.oriole.common.util.JacksonUtil;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 *
 * @author doublelife
 * Date: 2020/9/13 20:03
 * description:
 */
public class PageableUtil {

    public static Pageable getPageable(OriolePage page) {
        if (page.getSortParams() == null || page.getSortParams().size() == 0) {
            return PageRequest.of(page.getCurrentPage() - 1, page.getPageSize());
        }
        List<Sort.Order> orders = new ArrayList<>();
        String sortAsc = Sort.Direction.ASC.toString();
        page.getSortParams().forEach(sortParam -> {
            String[] param = sortParam.split(",");
            Sort.Order order;
            if (sortAsc.equalsIgnoreCase(param[1])) {
                order = new Sort.Order(Sort.Direction.ASC, param[0]);
            } else {
                order = new Sort.Order(Sort.Direction.DESC, param[0]);
            }
            orders.add(order);
        });
        return PageRequest.of(page.getCurrentPage() - 1, page.getPageSize(), Sort.by(orders));
    }

    public static OrioleResultPage<Object> setResultPage(ResultModel<Object> resultModel) {
        String data = JacksonUtil.pojo2Json(resultModel.getData());
        Map<String, Object> map = JacksonUtil.json2Map(data);
        OrioleResultPage<Object> resultPage = new OrioleResultPage<>();
        resultPage.setCurrentPage(Integer.parseInt(map.get("number").toString()) + 1);
        resultPage.setPageSize(Integer.parseInt(map.get("size").toString()));
        resultPage.setTotal(Integer.parseInt(map.get("totalElements").toString()));
        resultPage.setContent(map.get("content"));
        return resultPage;
    }

}
